package com.kuang;

import org.junit.Test;

import java.io.*;

/**
 * ClassName: FileReaderWriterTest
 * Description:
 * Date: 2021/3/17 11:04
 * Company: TravelSky
 *
 * @author YangXin
 */
public class FileReaderWriterTest {

    @Test
    public void test() throws IOException {
        FileReader fileReader = null;
        try {
            //实例化file对象,指明要操作文件
            File file = new File("src\\main\\resources\\imgs\\hello.txt");
            //提供具体的流
            fileReader = new FileReader(file);
            //数据的读入
            //read():返回读入的一个字符,如果达到文件末尾,返回-1
            int data ;
            while ((data = fileReader.read()) != -1) {
                System.out.print((char) data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //流的关闭操作
                if (fileReader != null)
                fileReader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test1() {
        FileReader fileReader = null;
        try {
            //实例化file对象,指明要操作文件
            File file = new File("src\\main\\resources\\imgs\\hello.txt");
            //提供具体的流
            fileReader = new FileReader(file);
            //数据的读入
            //read(char[] cbuf):返回每次读入数组的个数,末尾返回-1
            char[] cbuf = new char[3];
            int len ;
            while ((len = fileReader.read(cbuf)) != -1) {
                //错误的写法
//                for (int i = 0; i < cbuf.length; i++) {
//                    System.out.print(cbuf[i]);
//                }
                for (int i = 0; i < len; i++) {
                    System.out.print(cbuf[i]);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //流的关闭操作
                if (fileReader != null)
                fileReader.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    @Test
    public void test2() {
        FileWriter fileWriter = null;
        try {
            //实例化file对象,指明要操作文件
            File file = new File("src\\main\\resources\\imgs\\hello1.txt");
            //提供具体的写出流
            //append如果为true,不会对源文件覆盖,在后面追加,false的话覆盖,默认false
            fileWriter = new FileWriter(file,true);
            //数据的写出
            fileWriter.write("杨鑫\n");
            fileWriter.write("I have a dream");
            fileWriter.write("Audi RS7");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //流的关闭操作
                if (fileWriter != null)
                fileWriter.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

}
